package com.codingfly.core.jdbc.service.impl;

import com.codingfly.core.jdbc.service.JPAService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

@SuppressWarnings("unchecked")
public class JPAServiceImpl<M extends JpaRepository<T, ID>, T, ID> implements JPAService<T, ID> {

    @Autowired
    protected M jpaRepository;

    @Override
    public T findById(ID id) {
        Optional<T> optional = jpaRepository.findById(id);
        return optional.isPresent()? optional.get():null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(T entity) {
        jpaRepository.save(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(T[] entities) {
        if (ObjectUtils.isEmpty(entities)) {
            return ;
        }
        jpaRepository.saveAll(Arrays.asList(entities));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(List<T> entities) {
        if (ObjectUtils.isEmpty(entities)) {
            return;
        }
        jpaRepository.saveAll(entities);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(T entity) {
        if (entity!=null) {
            jpaRepository.delete(entity);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(T[] entities) {
        if (ObjectUtils.isEmpty(entities)) {
            return ;
        }
        jpaRepository.deleteAll(Arrays.asList(entities));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<T> entities) {
        if (ObjectUtils.isEmpty(entities)) {
            return ;
        }
        jpaRepository.deleteAll(entities);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(ID id) {
        if (id!=null) {
            jpaRepository.deleteById(id);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(ID[] ids) {
        if (ObjectUtils.isEmpty(ids)) {
            return ;
        }
        jpaRepository.deleteAllByIdInBatch(Arrays.asList(ids));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(List<ID> ids) {
        if (ObjectUtils.isEmpty(ids)) {
            return ;
        }
        jpaRepository.deleteAllByIdInBatch(ids);
    }

    @Override
    public Page<T> page(Pageable pageable) {
        return jpaRepository.findAll(pageable);
    }

    @Override
    public List<T> findAll() {
        return jpaRepository.findAll();
    }

}